<template>
  <div>
    <el-form v-loading="formLoading" :model="cuForm" size="mini" :rules="rules" ref="cuForm">
      <div style="width: 90%;margin: 10px auto 20px auto" class="flex justify-center">
        <el-form-item style="display: inline-block" prop="year" label="年" label-width="50px">
          <el-date-picker :disabled="edit"
                          v-model="cuForm.year"
                          type="year"
                          placeholder="选择年"
                          :picker-options="pickerOptions"
                          value-format="yyyy" @change="yearChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item style="display: inline-block;margin-left: 20px" label="年度" label-width="50px" prop="type">
          <el-select :disabled="edit" v-model="cuForm.type" placeholder="请选择" clearable @change="typeChange">
            <el-option :value="1" label="上半年"></el-option>
            <el-option :value="2" label="下半年"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目标" label-width="50px" prop="target">
          <el-input v-model="cuForm.target" :disabled="edit" type="number" step="0.0.1">
            <template slot="append">万元</template>
          </el-input>
        </el-form-item>
      </div>
      <el-row>
        <el-col :span="edit?12:18">
          <table class="mailTable">
            <template v-if="(cuForm.weekArr||[]).length>0" v-for="(item,index) in cuForm.weekArr">
              <tr :class="index===0?'firstTr':''" v-for="(tmp,i) in item.time">
                <td v-if="i===0" style="width: 10%" class="firstTd" rowspan="4" colspan="2">
                  {{ item.month }}月
                </td>
                <td style="width: 15%">
                  第{{ i + 1 }}周
                </td>
                <td style="padding: 0;width: 75%;">
                  <el-form-item :prop="'weekArr.' + index+'.time.'+ i + '.date'"
                                :rules="{required: true, message: '时间段不能为空', trigger: 'change'}"
                  >
                    <el-date-picker v-model="tmp.date" :disabled="edit"
                                    type="daterange"
                                    range-separator="至" start-placeholder="开始日期"
                                    end-placeholder="结束日期" :default-value="getDefaultValue(item.month)"
                                    value-format="yyyy-MM-dd" @change="(val)=>{dateChange(val,tmp)}"
                    >
                    </el-date-picker>
                  </el-form-item>
                </td>
              </tr>
            </template>
          </table>
        </el-col>
        <el-col :span="edit?12:6" style="position: relative">
          <div style="position: absolute;right: 40px;top:-35px">
            <el-button plain size="mini" @click="exportExcel">导出</el-button>
          </div>
          <table class="mailTable" id="data_table" v-loading="tableLoading">
            <tr class="firstTr">
              <td style="width: 20%" class="firstTd">
                销售员
              </td>
              <td style="width: 40%">
                目标额度
              </td>
              <td v-show="edit" style="width: 20%">已完成额度</td>
              <td v-show="edit" style="width: 20%">剩余额度</td>
            </tr>
            <tr v-for="(tmp,i) in cuForm.userTargetList" :key="i">
              <td class="firstTd" style="position: relative">{{ tmp.name + (tmp.status === 0 ? '（已离职）' : '') }}
                <div v-show="edit && tmp.status === 0 && tmp.target != tmp.complete_amount"
                     style="position: absolute;top: 0;left: -30px;"
                >
                  <el-tooltip effect="dark" content="将完成额度校准为此人员的目标" placement="top">
                    <i style="font-size: 20px;color: #409EFF;line-height: 40px"
                       class="el-icon-aim"
                       @click="calibration(tmp.user_id,cuForm.year,cuForm.type,tmp.complete_amount,tmp)"
                    ></i>
                  </el-tooltip>
                </div>
              </td>
              <td>
                <el-form-item :prop="'userTargetList.' + i+'.target'"
                              :rules="{required: true, message: '目标不能为空', trigger: 'blur'}"
                >
                  <el-input v-if="!exporting" v-model="tmp.target" :disabled="edit&&!tmp.can_edit" type="number"
                            step="0.01" clearable
                  >
                    <template slot="append">万</template>
                  </el-input>
                  <span v-else>{{ tmp.target + '万' }}</span>
                </el-form-item>
              </td>
              <td v-show="edit">
                {{ tmp.complete_amount ? tmp.complete_amount + '万' : tmp.complete_amount }}
              </td>
              <td v-show="edit">
                {{ getRemainderAmount(tmp.target, tmp.complete_amount) }}
              </td>
            </tr>
          </table>
          <div style="width: 90%;margin: 0 auto;text-align: right">目标额度合计：{{ summary }}元</div>
        </el-col>
      </el-row>
    </el-form>
    <div style="margin: 10px;text-align: center">
      <el-button @click="closeThisPage">返回</el-button>
      <el-button v-show="hasSaveBtn" type="primary" @click="submit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { list_by_role_code } from '@/api/system/user'
import { add, calibration, detail, replenish } from '@/api/workbench/saleYearTarget'
import { subtract, add as money_add } from '@/utils/amount'
import XLSX from 'xlsx'
import { formatDateByFmt } from '@/utils/util'

export default {
  name: 'index',
  async created() {
    const uuid = this.$route.query.uuid
    const params = this.$store.state.keep.pageParamsMap.get(uuid)
    if (params.id) {
      this.formLoading = true
      await detail({ year_id: params.id }).then(res => {
        this.cuForm.year = res.data.year
        this.cuForm.type = res.data.type
        this.cuForm.target = res.data.target
        this.cuForm.userTargetList = res.data.userTargetList
        let map = new Map()
        res.data.weekList.forEach(item => {
          if (map.has(item.month)) {
            let arr = map.get(item.month).time
            arr.push({
              date: [item.begin_date, item.end_date],
              begin: item.begin_date,
              end: item.end_date
            })
          } else {
            let arr = []
            arr.push({
              date: [item.begin_date, item.end_date],
              begin: item.begin_date,
              end: item.end_date
            })
            map.set(item.month, {
              month: item.month,
              time: arr
            })
          }
        })
        this.cuForm.weekArr = []
        map.forEach((value) => {
          this.cuForm.weekArr.push(value)
        })
        this.formLoading = false
      })
      //修改
      this.edit = true
    }
    this.oldYear = this.cuForm.year
    this.initSaleArr()
  },
  computed: {
    hasSaveBtn() {
      for (let i = 0; i < this.cuForm.userTargetList.length; i++) {
        if (this.cuForm.userTargetList[i].can_edit) {
          return true
        }
      }
      return false
    },
    summary() {
      let sum = 0
      for (let i = 0; i < this.cuForm.userTargetList.length; i++) {
        if (this.cuForm.userTargetList[i].target) {
          sum = money_add(sum, this.cuForm.userTargetList[i].target)
        }
      }
      return sum
    }
  },
  data() {
    return {
      cuForm: {
        year: new Date().getFullYear() + '',
        type: 1,
        target: null,
        weekArr: [
          {
            month: 1,
            time: [
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null }
            ]
          },
          {
            month: 2,
            time: [
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null }
            ]
          },
          {
            month: 3,
            time: [
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null }
            ]
          },
          {
            month: 4,
            time: [
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null }
            ]
          },
          {
            month: 5,
            time: [
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null }
            ]
          },
          {
            month: 6,
            time: [
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null },
              { date: null, begin: null, end: null }
            ]
          }
        ],
        userTargetList: [],
        weekList: []
      },
      oldYear: null,
      tableLoading: false,
      edit: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getFullYear() < new Date().getFullYear()
        }
      },
      rules: {
        year: [
          { required: true, message: '请选择年', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择年度', trigger: 'change' }
        ],
        target: [
          { required: true, message: '请输入目标', trigger: 'blur' }
        ]
      },
      formLoading: false,
      exporting: false
    }
  },
  methods: {
    typeChange(val, flag = false) {
      if (!flag) {
        let need_tip = false
        for (let i = 0; i < this.cuForm.weekList.length; i++) {
          if (this.cuForm.weekList[i].start_date !== null) {
            need_tip = true
            break
          }
        }
        if (need_tip) {
          this.$confirm('切换年度将清空选择的周数据？确定切换', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.clearWeekData(val)
          }).catch(() => {
            this.cuForm.type = val === 1 ? 2 : 1
          })
        } else {
          this.clearWeekData(val)
        }
      } else {
        this.clearWeekData(val)
      }
    },
    clearWeekData(val) {
      this.cuForm.weekArr = []
      let begin = 0
      if (val === 2) {
        begin = 6
      }
      for (let i = 1; i < 7; i++) {
        this.cuForm.weekArr.push({
          month: begin + i,
          time: [
            { date: null, begin: null, end: null },
            { date: null, begin: null, end: null },
            { date: null, begin: null, end: null },
            { date: null, begin: null, end: null }
          ]
        })
      }
    },
    initSaleArr() {
      this.tableLoading = true
      list_by_role_code({ code: 'Salesperson' }).then(res => {
        res.data.forEach(user => {
          this.tableLoading = false
          let find = this.cuForm.userTargetList.find(item => item.user_id === user.id)
          if (find === undefined) {
            if (user.status === 1) {
              this.cuForm.userTargetList.push({
                user_id: user.id,
                name: user.name,
                target: null,
                can_edit: true
              })
            }
          }
        })
      })
    },
    getDefaultValue(month) {
      var showDateBegin = this.cuForm.year + '-' + month + '-01'
      var showDateEnd = this.cuForm.year + '-' + month + '-28'
      return [new Date(showDateBegin), new Date(showDateEnd)]
    },
    yearChange(val) {
      let flag = false
      for (let i = 0; i < this.cuForm.weekList.length; i++) {
        if (this.cuForm.weekList[i].start_date !== null) {
          flag = true
          break
        }
      }
      if (flag) {
        this.$confirm('切换年将清空选择的周数据？确定切换', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.oldYear = val
          this.typeChange(this.cuForm.type, true)
        }).catch(() => {
          this.cuForm.year = this.oldYear
        })
      } else {
        this.typeChange(this.cuForm.type, true)
      }
    },
    submit() {
      this.$refs.cuForm.validate(flag => {
        if (flag) {
          if (this.summary == this.cuForm.target) {
            this.$confirm('保存后无法修改此次保存的数据,确定保存？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              const loading = this.$loading({
                lock: true,
                text: '保存中',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
              })
              if (this.edit) {
                replenish(this.cuForm).then(res => {
                  if (res.code === 200) {
                    this.$message.success('保存成功')
                    this.closeThisPage()
                  } else {
                    this.$message.error('保存失败')
                  }
                  loading.close()
                }).catch(() => {
                  loading.close()
                })
              } else {
                add(this.cuForm).then(res => {
                  if (res.code === 200) {
                    this.$message.success('保存成功')
                    this.closeThisPage()
                  } else {
                    this.$message.error('保存失败')
                  }
                  loading.close()
                }).catch(() => {
                  loading.close()
                })
              }
            }).catch(() => {
            })
          } else {
            this.$message.error('所有销售员的目标总和不等于年度目标，请调整')
          }
        }
      })
    },
    dateChange(val, tmp) {
      tmp.begin = val[0]
      tmp.end = val[1]
    },
    closeThisPage() {
      this.$store.dispatch('tagsView/closePage', this.$route.name)
    },
    getRemainderAmount(target, complete_amount) {
      if (isNaN(complete_amount)) {
        return target ? target + '万' : target
      } else {
        let result = subtract(target, complete_amount)
        if (result < 0) {
          result = 0
        }
        return result ? result + '万' : result
      }
    },
    /**
     * 校准
     * @param user_id
     * @param year
     * @param type
     * @param complete_amount
     * @param data 此行的数据
     */
    calibration(user_id, year, type, complete_amount, data) {
      this.$confirm('校准后此销售员的年度目标将变为已完成额度，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '保存中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        calibration({
          user_id,
          year,
          type,
          complete_amount
        }).then(res => {
          data.target = complete_amount
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }).catch(() => {

      })
    },
    exportExcel() {
      this.exporting = true
      this.$nextTick(() => {
        var table_elt = document.getElementById('data_table')
        var workbook = XLSX.utils.table_to_book(table_elt)
        var ws = workbook.Sheets['Sheet1']
        XLSX.utils.sheet_add_aoa(ws, [])
        XLSX.writeFile(workbook, ('半年目标') + (formatDateByFmt(new Date(), 'yyyyMMddhhmmss') + Math.floor(Math.random() * (1000000 - 1) + 1)) + '.xlsx')
        this.exporting = false
      })
    }
  },
  watch: {
    'cuForm.weekArr': {
      handler(val) {
        let arr = []
        val.forEach(item => {
          item.time.forEach(date => {
            arr.push({
              start_date: date.begin,
              end_date: date.end
            })
          })
        })
        this.cuForm.weekList = arr
      },
      deep: true
    }
  }
}
</script>

<style scoped>
.mailTable {
  width: 90%;
  font-size: 14px;
  margin: 0 auto 10px auto;
  border-collapse: collapse;
}

.mailTable tr td {
  height: 40px;
  line-height: 35px;
  box-sizing: border-box;
  padding: 0 10px;
  border-bottom: 1px solid #E6EAEE;
  border-right: 1px solid #E6EAEE;
  text-align: center;
}

.firstTr td {
  border-top: 1px solid #E6EAEE;
}

.firstTd {
  border-left: 1px solid #E6EAEE;
}

.mailTable tr td.column {
  text-align: center;
  /*border: 1px solid #8c939d;*/
}

.header {
  text-align: center;
  font-size: 25px;
  font-weight: bold;
  margin: 10px auto;
}

.required {
  color: red;
}

/deep/ .el-form-item {
  margin-bottom: 0;
}

/deep/ .el-form-item__content {
  line-height: 0;
  text-align: center;
}

/deep/ td .el-form-item__error {
  position: relative;
  padding: 3px;
}

/deep/ .el-textarea.is-disabled .el-textarea__inner {
  background-color: white;
  color: black;
}

/deep/ .el-input.is-disabled .el-input__inner {
  background-color: white;
  color: black;
}

/deep/ .el-range-editor.is-disabled input {
  background-color: white;
  color: black;
}

/deep/ .el-range-editor.is-disabled {
  background-color: white;
  color: black;
}

/deep/ .el-range-editor.is-disabled .el-range-separator {
  color: black;
}
</style>
